package com.cherry.androidcode.activity

import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.ViewGroup
import android.webkit.*
import com.cherry.androidcode.R
import com.cherry.androidcode.base.BaseTitleBarActivity
import com.cherry.androidcode.helper.WebViewHelper
import kotlinx.android.synthetic.main.activity_webview.*


/**
 * @author DongMS
 * @date 2019/6/20
 */
class WebViewActivity : BaseTitleBarActivity() {
    override val titleText = R.string.app_name

    private var isRefresh = true

    override val contentLayoutRes = R.layout.activity_webview

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        WebViewHelper.setup(webview)
        //处理各种通知 & 请求事件
        webview.webViewClient = WebClient()
        //辅助 WebView 处理 Javascript 的对话框,网站图标,网站标题等等
        webview.webChromeClient = WebChrome()

        webview.loadUrl(intent.getStringExtra("url"))

        //方式1. 加载一个网页：
//        webview.loadUrl("https://mtest.ilaisa.com/mall/?ticket=NTEzNzg5QTMxLTFGRkMtOThERi04N0NFLUVGOENGODA2RjlGNA==#/apply_admin")
//        webview.loadUrl("http://404.html")

        //方式2：加载apk包中的html页面
//        webview.loadUrl("file:///android_asset/testJs.html")

        //方式3：加载手机本地sd卡根目录的html页面
//        webview.loadUrl("content://com.android.htmlfileprovider/sdcard/test.html")

        initWebViewController()

    }

    private fun initWebViewController() {
        tv_forward.setOnClickListener {
            if (webview.canGoForward()) {
                webview.goForward()
            }
        }
        tv_back.setOnClickListener {
            if (webview.canGoBack()) {
                webview.goBack()
            }
        }
        tv_refresh_stop.setOnClickListener {
            if (isRefresh) {
                webview.reload()
            } else {
                webview.stopLoading()
            }
        }

    }


    ////////////////////////////
    private inner class WebChrome : WebChromeClient() {
        //获得网页的加载进度并显示
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            webview.progress = newProgress
        }

        //获取Web页中的标题
        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
            actionBar?.title = title
        }

        //一般情况下在 Android 中为 Toast，在文本里面加入\n就可以换行
        override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
            return super.onJsAlert(view, url, message, result)
        }

        //支持javascript的确认框
        override fun onJsConfirm(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
            return super.onJsConfirm(view, url, message, result)
        }

        //支持javascript输入框
        override fun onJsPrompt(view: WebView?, url: String?, message: String?, defaultValue: String?, result: JsPromptResult?): Boolean {
            return super.onJsPrompt(view, url, message, defaultValue, result)
        }
    }


    ///////////////////////////////
    private inner class WebClient : WebViewClient() {

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            webview.start()
            isRefresh = false
            tv_refresh_stop.text = "停止"
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            isRefresh = true
            tv_refresh_stop.text = "刷新"
        }

        //在加载页面资源时会调用，每一个资源（比如图片）的加载都会调用一次
        override fun onLoadResource(view: WebView?, url: String?) {
            super.onLoadResource(view, url)
        }

        //加载页面的服务器出现错误时（如404）调用
        override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {
            super.onReceivedError(view, errorCode, description, failingUrl)
            Log.e("webview----error", "errorCode:$errorCode:description[$description]")
            //测试加载一个自定义的错误界面
            webview.loadUrl("file:///android_asset/testJs.html")
        }

        //webView默认是不处理https请求的，页面显示空白
        override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
            super.onReceivedSslError(view, handler, error)
            Log.e("webview--error---https", "errorCode:${error?.primaryError}")
            handler?.proceed()  //表示等待证书响应
            // handler.cancel();      //表示挂起连接，为默认方式
            // handler.handleMessage(null);    //可做其他处理
        }

    }


    ///////////////webview回到上一个页面/////////////////
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK && event.action === KeyEvent.ACTION_DOWN) {
            backWeb {
                finish()
            }
            true
        } else {
            super.onKeyDown(keyCode, event)
        }
    }

    override fun onBackPressed() {
        backWeb {
            super.onBackPressed()
        }
    }

    private fun backWeb(lastBack: () -> Unit) {
        if (webview.canGoBack()) {
            //判断用户如果返回的回次在俩次以内直接关闭activity ，可自行设置
            //                if (webview.copyBackForwardList().size <= 2) {
            //                    finish()
            //                } else {
            webview.goBack()
            //                }
        } else {
            lastBack.invoke()
        }
    }

    //////////////////解决webview的内存泄漏////////////////////
    override fun onDestroy() {
        //先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再destory()
        val parent = webview.parent
        (parent as? ViewGroup)?.removeView(webview)
        webview.stopLoading()
        // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
        webview.settings.javaScriptEnabled = false
        WebViewHelper.clear(webview)
        webview.clearView()
        webview.removeAllViews()
        webview.destroy()
        super.onDestroy()
    }


}